package com.dongdongshop.shiro;

import com.dongdongshop.admin.model.TbUser;
import com.dongdongshop.admin.vo.TbUserVO;
import com.dongdongshop.api.SellerServiceApi;
import com.dongdongshop.common.Result;
import com.dongdongshop.dto.SellerDTO;
import com.dongdongshop.em.TokenEnum;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.service.TUserservice;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.ByteSource.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(LoginRealm.class);
    @Autowired
    private TUserservice userService;
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        TbUser admin = (TbUser)SecurityUtils.getSubject().getPrincipal();
        this.logger.info("授权,用户{}", admin.getUsername());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.logger.info("登录");
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //获取账号
        String personname = token.getUsername();
        TbUser result = this.userService.findTbUserByName(personname);
            if (result == null) {
                return null;
            } else if (!result.getStatus().equals("Y")) {
                throw new LoginException("账号异常,请联系客服人员");
            } else {
                return new SimpleAuthenticationInfo(result, result.getPassword(), Util.bytes(result.getSalt()), "LoginRealm");
            }
    }
}